<template>
  <div class="certificates-container">
    <div class="header">
      <h2>证书管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="success" @click="handleExportExcel" style="margin-left: 10px;">
          <el-icon><Download /></el-icon>
          <span>导出Excel</span>
        </el-button>
      </div>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.employee_name"
        placeholder="搜索员工姓名"
        style="width: 200px"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <div class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        :fit="true"
        size="small"
      >
        <el-table-column prop="employee_name" label="员工姓名" min-width="120" show-overflow-tooltip />
        <el-table-column prop="name" label="证书名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="certificate_no" label="证书编号" min-width="150" show-overflow-tooltip />
        <el-table-column prop="level" label="证书级别" width="120" show-overflow-tooltip />
        <el-table-column prop="issuing_org" label="发证机构" min-width="180" show-overflow-tooltip />
        <el-table-column prop="issue_date" label="获得日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.issue_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="expiry_date" label="有效期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.expiry_date) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="180" max-width="240" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button size="small" type="warning" @click="handleView(scope.row)">
                <el-icon><View /></el-icon>
                <span>查看</span>
              </el-button>
              <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>
                <span>编辑</span>
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑证书对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加证书' : dialogType === 'edit' ? '编辑证书' : '查看证书'"
      width="80%"
      style="max-width: 1200px"
      :destroy-on-close="true"
      class="certificate-dialog adaptive-dialog"
      top="5vh"
    >
      <div class="dialog-content adaptive-dialog-content">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          :disabled="dialogType === 'view'"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="员工姓名" prop="employee_id">
                <el-select
                  v-model="form.employee_id"
                  placeholder="请选择员工"
                  style="width: 100%"
                  :disabled="dialogType === 'view'"
                >
                  <el-option
                    v-for="emp in employees"
                    :key="emp.id"
                    :label="emp.name"
                    :value="emp.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="证书名称" prop="name">
                <el-select v-model="form.name" placeholder="请选择证书名称" filterable allow-create style="width: 100%" :disabled="dialogType === 'view'">
                  <el-option v-for="item in certificateNameOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证书编号" prop="certificate_number">
                <el-input v-model="form.certificate_number" placeholder="请输入证书编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发证机构" prop="issuing_org">
                <el-input v-model="form.issuing_org" placeholder="请输入发证机构" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发证日期" prop="issue_date">
                <el-date-picker
                  v-model="form.issue_date"
                  type="date"
                  placeholder="请选择发证日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="有效期至" prop="expiry_date">
                <el-date-picker
                  v-model="form.expiry_date"
                  type="date"
                  placeholder="请选择有效期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="证书级别" prop="level">
                <el-select v-model="form.level" placeholder="请选择证书级别" style="width: 100%">
                  <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-tag :type="getStatusTagType(form.expiry_date)">{{ getStatusText(form.expiry_date) }}</el-tag>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-model="form.remarks"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 附件列表 -->
        <div class="attachment-section">
          <div class="attachment-card attachment-card-with-label">
            <span class="attachment-card-label">附件列表</span>
            <div class="attachment-card-content">
              <attachment-list
                :attachments="certificateAttachments"
                :loading="attachmentsLoading"
                :readonly="dialogType === 'view'"
                :download-function="downloadAttachment"
                :delete-function="deleteAttachment"
                :preview-function="previewAttachment"
                @add-attachment="handleAddAttachment"
                @refresh="loadCertificateAttachments"
              />
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            v-if="dialogType !== 'view'"
            type="primary"
            @click="submitForm"
            :loading="submitting"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 附件上传对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传附件"
      width="500px"
      @closed="handleUploadDialogClosed"
    >
      <AttachmentUploader
        module="certificates"
        :moduleId="currentId"
        @upload-success="handleUploadSuccess"
      />
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUploadDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Download, View, Edit, Delete } from '@element-plus/icons-vue'
import { certificateAPI, employeeAPI, certificateNameAPI } from '../api'
import { getDictItemsByCode } from '../api/dict'
import AttachmentList from '../components/AttachmentList.vue'
import AttachmentUploader from '../components/AttachmentUploader.vue'

export default {
  name: 'Certificates',
  components: {
    Search, Plus, Download, View, Edit, Delete,
    AttachmentList,
    AttachmentUploader
  },
  setup() {
    // 表格数据
    const tableData = ref([])
    const loading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 搜索表单
    const searchForm = ref({
      employee_name: ''
    })
    
    // 新增/编辑表单
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const formRef = ref(null)
    const form = ref({
      id: null,
      employee_id: '',
      name: '',
      certificate_no: '',
      level: '',
      issuing_org: '',
      issue_date: '',
      expiry_date: '',
      description: ''
    })
    
    // 员工选择相关
    const employeeOptions = ref([])
    const employeeLoading = ref(false)
    
    // 附件相关
    const currentId = ref(null)
    const certificateAttachments = ref([])
    const attachmentsLoading = ref(false)
    const showUploadDialog = ref(false)
    
    // 证书名称选项
    const certificateNameOptions = ref([])
    
    // 员工下拉选项
    const employees = ref([])
    
    // 表单验证规则
    const rules = {
      employee_id: [
        { required: true, message: '请选择员工', trigger: 'change' }
      ],
      name: [
        { required: true, message: '请输入证书名称', trigger: 'blur' }
      ],
      certificate_no: [
        { required: true, message: '请输入证书编号', trigger: 'blur' }
      ],
      issuing_org: [
        { required: true, message: '请输入发证机构', trigger: 'blur' }
      ],
      issue_date: [
        { required: true, message: '请选择获得日期', trigger: 'change' }
      ]
    }
    
    // 获取证书列表
    const getCertificateList = async () => {
      loading.value = true
      try {
        const response = await certificateAPI.getAll(currentPage.value, pageSize.value, searchForm.value)
        tableData.value = response.data.items
        total.value = response.data.total
      } catch (error) {
        ElMessage.error('获取证书列表失败')
        console.error('获取证书列表失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      currentPage.value = 1
      getCertificateList()
    }
    
    // 重置搜索
    const resetSearch = () => {
      searchForm.value = {
        employee_name: ''
      }
      handleSearch()
    }
    
    // 新增
    const handleAdd = () => {
      dialogType.value = 'add'
      form.value = {
        id: null,
        employee_id: '',
        name: '',
        certificate_no: '',
        level: '',
        issuing_org: '',
        issue_date: '',
        expiry_date: '',
        description: ''
      }
      currentId.value = null
      certificateAttachments.value = []
      dialogVisible.value = true
    }
    
    // 编辑
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      form.value = { ...row }
      currentId.value = row.id
      dialogVisible.value = true
      loadCertificateAttachments()
    }
    
    // 查看
    const handleView = (row) => {
      dialogType.value = 'view'
      form.value = { ...row }
      currentId.value = row.id
      dialogVisible.value = true
      loadCertificateAttachments()
    }
    
    // 删除
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确定要删除此证书吗？删除后无法恢复。',
        '警告',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await certificateAPI.delete(row.id)
          ElMessage.success('删除成功')
          getCertificateList()
        } catch (error) {
          ElMessage.error('删除证书失败')
          console.error('删除证书失败:', error)
        }
      }).catch(() => {})
    }
    
    // 分页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val
      getCertificateList()
    }
    
    // 当前页改变
    const handleCurrentChange = (val) => {
      currentPage.value = val
      getCertificateList()
    }
    
    // 远程搜索员工
    const remoteSearchEmployee = async (query) => {
      if (query) {
        employeeLoading.value = true
        try {
          const response = await employeeAPI.search(query)
          employeeOptions.value = response.data
        } catch (error) {
          console.error('搜索员工失败:', error)
        } finally {
          employeeLoading.value = false
        }
      } else {
        employeeOptions.value = []
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (dialogType.value === 'add') {
              await certificateAPI.create(form.value)
              ElMessage.success('新增成功')
            } else {
              await certificateAPI.update(form.value.id, form.value)
              ElMessage.success('更新成功')
            }
            dialogVisible.value = false
            getCertificateList()
          } catch (error) {
            ElMessage.error(dialogType.value === 'add' ? '新增证书失败' : '更新证书失败')
            console.error(dialogType.value === 'add' ? '新增证书失败:' : '更新证书失败:', error)
          }
        }
      })
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      return date.split('T')[0]
    }
    
    // 加载证书附件
    const loadCertificateAttachments = async () => {
      if (!currentId.value) {
        certificateAttachments.value = []
        return
      }
      
      attachmentsLoading.value = true
      try {
        const response = await certificateAPI.getAttachments(currentId.value)
        certificateAttachments.value = response.data || []
      } catch (error) {
        ElMessage.error('获取附件列表失败')
        console.error('获取附件列表失败:', error)
        certificateAttachments.value = []
      } finally {
        attachmentsLoading.value = false
      }
    }
    
    // 上传证书附件
    const uploadCertificateAttachment = (certificateId, file, description) => {
      return certificateAPI.addAttachment(certificateId, file, description)
    }
    
    // 处理上传成功
    const handleUploadSuccess = () => {
      ElMessage.success('附件上传成功')
      loadCertificateAttachments()
    }
    
    // 下载附件
    const downloadAttachment = (attachmentId) => {
      return certificateAPI.download(attachmentId)
    }
    
    // 删除附件
    const deleteAttachment = (attachmentId) => {
      return certificateAPI.deleteAttachment(currentId.value, attachmentId)
    }
    
    // 预览附件
    const previewAttachment = (attachmentId) => {
      return certificateAPI.getPreviewUrl(attachmentId)
    }
    
    // 处理添加附件
    const handleAddAttachment = () => {
      if (!currentId.value) {
        ElMessage.warning('请先保存证书基本信息')
        return
      }
      showUploadDialog.value = true
    }
    
    // 关闭对话框时的清理
    const handleDialogClosed = () => {
      currentId.value = null
      certificateAttachments.value = []
    }
    
    // 关闭上传对话框
    const handleUploadDialogClosed = () => {
      loadCertificateAttachments()
    }
    
    // 获取证书名称选项
    const loadCertificateNames = async () => {
      try {
        const res = await certificateNameAPI.getAll(1, 1000, {})
        // 兼容 res.data、res.data.data、res.data.items 三种情况
        let arr = []
        if (Array.isArray(res.data)) {
          arr = res.data
        } else if (Array.isArray(res.data.data)) {
          arr = res.data.data
        } else if (Array.isArray(res.data.items)) {
          arr = res.data.items
        }
        certificateNameOptions.value = arr.map(item => ({
          label: item.name + (item.level ? `（${item.level}）` : ''),
          value: item.name,
          issuing_org: item.issuing_org
        }))
      } catch (e) {
        certificateNameOptions.value = []
      }
    }
    
    // 监听弹窗打开时刷新证书名称下拉框
    watch(dialogVisible, (val) => {
      if (val) {
        loadCertificateNames()
      }
    })
    
    // 证书名称变化时自动联动发证机构
    watch(
      () => form.value.name,
      (newName) => {
        const selected = certificateNameOptions.value.find(item => item.value === newName)
        if (selected && selected.issuing_org) {
          form.value.issuing_org = selected.issuing_org
        } else {
          form.value.issuing_org = ''
        }
      }
    )
    
    // 加载员工列表
    const loadEmployees = async () => {
      try {
        const res = await employeeAPI.getAll(1, 1000, {})
        employees.value = res.data.data || []
      } catch (e) {
        employees.value = []
      }
    }
    
    // 证书状态实时判断
    function getStatusText(expiryDate) {
      if (!expiryDate) return '未知';
      const now = new Date();
      const exp = new Date(expiryDate);
      const diff = exp - now;
      if (diff < 0) return '已过期';
      if (diff < 30 * 24 * 60 * 60 * 1000) return '即将过期';
      return '有效';
    }
    function getStatusTagType(expiryDate) {
      if (!expiryDate) return 'info';
      const now = new Date();
      const exp = new Date(expiryDate);
      const diff = exp - now;
      if (diff < 0) return 'danger';
      if (diff < 30 * 24 * 60 * 60 * 1000) return 'warning';
      return 'success';
    }
    
    // 处理导出Excel
    const handleExportExcel = async () => {
      try {
        const res = await certificateAPI.exportExcel()
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = '证书列表.xlsx'
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
        ElMessage.success('导出成功')
      } catch (e) {
        ElMessage.error('导出失败，请稍后重试')
        console.error('导出证书列表失败:', e)
      }
    }
    
    // 证书级别选项
    const levelOptions = ref([])
    
    onMounted(() => {
      getCertificateList()
      loadCertificateNames()
      loadEmployees()
      getDictItemsByCode('CERT_LEVEL').then(res => {
        levelOptions.value = res.data
      })
    })
    
    onUnmounted(() => {
      // 移除 resize 事件监听
      // window.removeEventListener('resize', handleTableResize)
    })
    
    return {
      tableData,
      loading,
      currentPage,
      pageSize,
      total,
      searchForm,
      dialogVisible,
      dialogType,
      formRef,
      form,
      rules,
      employeeOptions,
      employeeLoading,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      remoteSearchEmployee,
      submitForm,
      formatDate,
      Search,
      
      // 附件相关
      currentId,
      certificateAttachments,
      attachmentsLoading,
      showUploadDialog,
      loadCertificateAttachments,
      uploadCertificateAttachment,
      handleUploadSuccess,
      downloadAttachment,
      deleteAttachment,
      previewAttachment,
      handleDialogClosed,
      handleUploadDialogClosed,
      handleAddAttachment,
      handleView,
      
      // 证书名称选项
      certificateNameOptions,
      employees,
      getStatusText,
      getStatusTagType,
      handleExportExcel,
      Plus, Download, View, Edit, Delete,
      levelOptions
    }
  }
}
</script>

<style scoped>
.certificates-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.pagination-container {
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
}

/* 证书表单样式 */
.certificate-form {
  padding: 0 10px;
}

.form-section {
  margin-bottom: 30px;
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-top: 0;
  margin-bottom: 20px;
  color: #303133;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.no-attachments-info {
  margin-top: 10px;
}

/* 表格样式 */
:deep(.el-table) {
  margin-bottom: 20px;
  border: none;
}

:deep(.el-table__header) {
  background-color: #F5F7FA;
}

:deep(.el-table th) {
  background-color: #F5F7FA !important;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table .el-table__fixed-right) {
  background-color: #fff;
}

:deep(.el-table .el-table__fixed-right th) {
  background-color: #F5F7FA !important;
}

:deep(.el-table .el-table__fixed-right td) {
  background-color: #fff;
}

/* 对话框样式 */
:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f9f9f9;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
  padding-bottom: 0;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f9f9f9;
}

/* 按钮样式优化 */
:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-button--small.is-plain) {
  background-color: #fff;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-button--small.is-plain:hover) {
  background-color: #ecf5ff;
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-button--small.is-plain:active) {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .certificates-container {
    padding: 0;
  }

  .search-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  :deep(.el-form--inline .el-form-item) {
    margin-right: 0;
    width: 100%;
  }
}

.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.attachment-section {
  display: flex;
  flex-direction: column;
}

.attachment-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
}

:deep(.attachment-list) {
  display: flex;
  flex-direction: column;
}

:deep(.el-table) {
  width: 100%;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

.dialog-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #dcdfe6;
}

.attachment-card {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
}

.attachment-card-label {
  position: absolute;
  top: -12px;
  left: 16px;
  background: #fff;
  color: #409EFF;
  font-size: 15px;
  font-weight: 500;
  padding: 0 10px;
  z-index: 2;
  border-radius: 8px 8px 8px 0;
  box-shadow: 0 2px 8px 0 rgba(64,158,255,0.04);
  letter-spacing: 2px;
}

.attachment-card-with-label {
  position: relative;
  margin-top: 16px;
}

.attachment-card-content {
  display: flex;
  flex-direction: column;
}

.adaptive-dialog .el-dialog {
  margin: 0 auto;
  top: 5vh !important;
  transform: none !important;
}

.header-buttons .el-button span {
  margin-left: 4px;
}

:deep(.action-buttons) {
  display: flex;
  gap: 8px;
  min-width: 180px;
  max-width: 240px;
  flex-wrap: nowrap;
  white-space: nowrap;
}
</style> 